"""
任务API路由
"""

from flask import Blueprint, request, jsonify
from flask_jwt_extended import jwt_required, get_jwt_identity
from app.models.task import Task, TaskStatus, TaskPriority
from app.models.user import User
from app.models.project import Project
from app import db
from app.utils.decorators import validate_json
from app.utils.validators import validate_task_data
from datetime import datetime
import json
from marshmallow import ValidationError

tasks_bp = Blueprint('tasks', __name__)


@tasks_bp.route('/', methods=['GET'])
@jwt_required()
def get_tasks():
    """获取任务列表"""
    try:
        current_user_id = get_jwt_identity()
        page = request.args.get('page', 1, type=int)
        per_page = request.args.get('per_page', 20, type=int)
        status = request.args.get('status')
        assignee_id = request.args.get('assignee_id')
        project_id = request.args.get('project_id')
        
        # 构建查询
        query = Task.query
        
        # 过滤条件
        if status:
            query = query.filter_by(status=TaskStatus(status))
        if assignee_id:
            query = query.filter_by(assignee_id=assignee_id)
        if project_id:
            query = query.filter_by(project_id=project_id)
        
        # 分页
        tasks = query.paginate(
            page=page, 
            per_page=per_page, 
            error_out=False
        )
        
        return jsonify({
            'success': True,
            'tasks': [task.to_dict() for task in tasks.items],
            'pagination': {
                'page': page,
                'per_page': per_page,
                'total': tasks.total,
                'pages': tasks.pages,
                'has_next': tasks.has_next,
                'has_prev': tasks.has_prev
            }
        })
        
    except Exception as e:
        return jsonify({'error': str(e)}), 500


@tasks_bp.route('/<int:task_id>', methods=['GET'])
@jwt_required()
def get_task(task_id):
    """获取单个任务"""
    try:
        task = Task.query.get(task_id)
        if not task:
            return jsonify({'error': '任务不存在'}), 404
        
        return jsonify({
            'success': True,
            'task': task.to_dict()
        })
        
    except Exception as e:
        return jsonify({'error': str(e)}), 500


@tasks_bp.route('/', methods=['POST'])
@jwt_required()
def create_task():
    """创建任务"""
    try:
        current_user_id = get_jwt_identity()
        data = request.get_json()
        
        # 验证数据
        try:
            validated_data = validate_task_data(data)
        except ValidationError as e:
            return jsonify({'error': '数据验证失败', 'details': e.messages}), 400
        
        # 验证项目权限
        if validated_data.get('project_id'):
            project = Project.find_by_id(validated_data['project_id'])
            if not project:
                return jsonify({'error': '项目不存在'}), 404
            
            # 检查用户是否有权限访问项目
            if not project.can_access(current_user_id):
                return jsonify({'error': '无权限访问该项目'}), 403
        
        # 解析日期
        due_date = None
        if validated_data.get('due_date'):
            try:
                due_date = datetime.fromisoformat(validated_data['due_date'].replace('Z', '+00:00'))
            except ValueError:
                return jsonify({'error': '日期格式错误'}), 400
        
        # 解析优先级
        try:
            priority = TaskPriority(validated_data.get('priority', 'medium'))
        except ValueError:
            priority = TaskPriority.MEDIUM
        
        # 创建任务
        task = Task(
            title=validated_data['title'],
            description=validated_data.get('description', ''),
            creator_id=current_user_id,
            assignee_id=validated_data.get('assignee_id'),
            project_id=validated_data.get('project_id'),
            priority=priority,
            due_date=due_date,
            estimated_hours=validated_data.get('estimated_hours'),
            tags=','.join(validated_data.get('tags', [])) if validated_data.get('tags') else None
        )
        
        db.session.add(task)
        db.session.commit()
        
        return jsonify({
            'success': True,
            'message': '任务创建成功',
            'task': task.to_dict()
        }), 201
        
    except Exception as e:
        db.session.rollback()
        return jsonify({'error': str(e)}), 500


@tasks_bp.route('/<int:task_id>', methods=['PUT'])
@jwt_required()
def update_task(task_id):
    """更新任务"""
    try:
        current_user_id = get_jwt_identity()
        task = Task.query.get(task_id)
        
        if not task:
            return jsonify({'error': '任务不存在'}), 404
        
        # 检查权限（只有创建者或分配者可以修改）
        if task.creator_id != current_user_id and task.assignee_id != current_user_id:
            return jsonify({'error': '无权限修改此任务'}), 403
        
        data = request.get_json()
        updated = False
        
        # 更新字段
        if 'title' in data:
            task.title = data['title']
            updated = True
        
        if 'description' in data:
            task.description = data['description']
            updated = True
        
        if 'status' in data:
            task.update_status(TaskStatus(data['status']))
            updated = True
        
        if 'priority' in data:
            task.priority = TaskPriority(data['priority'])
            updated = True
        
        if 'assignee_id' in data:
            task.assignee_id = data['assignee_id']
            updated = True
        
        if 'due_date' in data:
            task.due_date = datetime.fromisoformat(data['due_date']) if data['due_date'] else None
            updated = True
        
        if 'estimated_hours' in data:
            task.estimated_hours = data['estimated_hours']
            updated = True
        
        if 'actual_hours' in data:
            task.actual_hours = data['actual_hours']
            updated = True
        
        if 'tags' in data:
            task.set_tags(data['tags'])
            updated = True
        
        if updated:
            task.updated_at = datetime.utcnow()
            db.session.commit()
            
            return jsonify({
                'success': True,
                'message': '任务更新成功',
                'task': task.to_dict()
            })
        else:
            return jsonify({
                'success': True,
                'message': '任务信息无变化',
                'task': task.to_dict()
            })
        
    except Exception as e:
        db.session.rollback()
        return jsonify({'error': str(e)}), 500


@tasks_bp.route('/<int:task_id>', methods=['DELETE'])
@jwt_required()
def delete_task(task_id):
    """删除任务"""
    try:
        current_user_id = get_jwt_identity()
        task = Task.query.get(task_id)
        
        if not task:
            return jsonify({'error': '任务不存在'}), 404
        
        # 检查权限（只有创建者可以删除）
        if task.creator_id != current_user_id:
            return jsonify({'error': '无权限删除此任务'}), 403
        
        db.session.delete(task)
        db.session.commit()
        
        return jsonify({
            'success': True,
            'message': '任务删除成功'
        })
        
    except Exception as e:
        db.session.rollback()
        return jsonify({'error': str(e)}), 500


@tasks_bp.route('/<int:task_id>/status', methods=['PUT'])
@jwt_required()
@validate_json(['status'])
def update_task_status(task_id):
    """更新任务状态"""
    try:
        current_user_id = get_jwt_identity()
        task = Task.query.get(task_id)
        
        if not task:
            return jsonify({'error': '任务不存在'}), 404
        
        # 检查权限
        if task.creator_id != current_user_id and task.assignee_id != current_user_id:
            return jsonify({'error': '无权限修改此任务'}), 403
        
        data = request.get_json()
        new_status = TaskStatus(data['status'])
        
        task.update_status(new_status)
        
        return jsonify({
            'success': True,
            'message': '任务状态更新成功',
            'task': task.to_dict()
        })
        
    except Exception as e:
        db.session.rollback()
        return jsonify({'error': str(e)}), 500


@tasks_bp.route('/my-tasks', methods=['GET'])
@jwt_required()
def get_my_tasks():
    """获取我的任务"""
    try:
        current_user_id = get_jwt_identity()
        page = request.args.get('page', 1, type=int)
        per_page = request.args.get('per_page', 20, type=int)
        status = request.args.get('status')
        
        # 构建查询
        query = Task.query.filter(
            (Task.creator_id == current_user_id) | 
            (Task.assignee_id == current_user_id)
        )
        
        if status:
            query = query.filter_by(status=TaskStatus(status))
        
        # 分页
        tasks = query.paginate(
            page=page, 
            per_page=per_page, 
            error_out=False
        )
        
        return jsonify({
            'success': True,
            'tasks': [task.to_dict() for task in tasks.items],
            'pagination': {
                'page': page,
                'per_page': per_page,
                'total': tasks.total,
                'pages': tasks.pages,
                'has_next': tasks.has_next,
                'has_prev': tasks.has_prev
            }
        })
        
    except Exception as e:
        return jsonify({'error': str(e)}), 500


@tasks_bp.route('/overdue', methods=['GET'])
@jwt_required()
def get_overdue_tasks():
    """获取过期任务"""
    try:
        current_user_id = get_jwt_identity()
        
        # 获取用户相关的过期任务
        overdue_tasks = Task.query.filter(
            (Task.creator_id == current_user_id) | 
            (Task.assignee_id == current_user_id),
            Task.due_date < datetime.utcnow(),
            Task.status != TaskStatus.DONE
        ).all()
        
        return jsonify({
            'success': True,
            'tasks': [task.to_dict() for task in overdue_tasks]
        })
        
    except Exception as e:
        return jsonify({'error': str(e)}), 500
